<template>
  <div class="app-container">
    <div class="filter-container">
      <!--      <el-select v-model="listQuery.projectId" placeholder="所属项目" class="filter-item">
        <el-option v-for="item in jobProjectList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="fetchData">
        搜索
      </el-button>-->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width: 100%"
      size="medium"
    >
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column label="源数据源" align="center">
        <template slot-scope="scope">
          {{
            getDictJdbcDsValue(scope.row.sourceSourceId)
              ? getDictJdbcDsValue(scope.row.sourceSourceId)
              : scope.row.sourceSourceId
          }}
        </template>
      </el-table-column>
      <el-table-column label="源数据库模式" align="center">
        <template slot-scope="scope">{{ scope.row.sourceSchema }}</template>
      </el-table-column>
      <el-table-column label="目标数据源" align="center">
        <template slot-scope="scope">
          {{
            getDictJdbcDsValue(scope.row.targetSourceId)
              ? getDictJdbcDsValue(scope.row.targetSourceId)
              : scope.row.targetSourceId
          }}
        </template>
      </el-table-column>

      <el-table-column label="目标数据库模式" align="center">
        <template slot-scope="scope">{{ scope.row.targetSchema }}</template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" width="120">
        <template slot-scope="scope">
          {{
            getDictJobProjectValue(scope.row.projectId)
              ? getDictJobProjectValue(scope.row.projectId)
              : scope.row.projectId
          }}
        </template>
      </el-table-column>
      <el-table-column label="任务模板" align="center" width="120">
        <template slot-scope="scope">
          {{
            getDictTemplateValue(scope.row.jobTemplateId)
              ? getDictTemplateValue(scope.row.jobTemplateId)
              : scope.row.jobTemplateId
          }}
        </template>
      </el-table-column>
      <el-table-column label="空间字段名称" align="center" width="120">
        <template slot-scope="scope">{{
          scope.row.spatialColumnName
        }}</template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="150">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1">启动</el-tag>
          <el-tag v-else type="danger">停止</el-tag>
          <!--          <el-switch
            v-model="scope.row.status"
            active-color="#00A854"
            active-text="启动"
            :active-value="1"
            inactive-color="#F04134"
            inactive-text="停止"
            :inactive-value="0"
            @change="changeSwitch(scope.row)"
          />-->
        </template>
      </el-table-column>
      <el-table-column label="上次同步时间" align="center" width="120">
        <template slot-scope="scope">{{ scope.row.lastSyncTime }}</template>
      </el-table-column>

      <el-table-column label="操作" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="text" size="small" @click.native="handlerUpdate(row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click.native="handlerDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchData"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="auto"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="源数据源：" prop="sourceSourceId">
              <el-select
                v-model="temp.sourceSourceId"
                placeholder="请选择源数据源"
                @change="rDsChange"
              >
                <el-option
                  v-for="item in rDsList"
                  :key="item.id"
                  :label="item.datasourceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="源数据源模式：" prop="sourceSchema">
              <el-select
                v-model="temp.sourceSchema"
                placeholder="请选择源数据源模式"
              >
                <el-option
                  v-for="item in schemaList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目标数据源：" prop="targetSourceId">
              <el-select
                v-model="temp.targetSourceId"
                placeholder="请选择目标数据源"
                @change="wDsChange"
              >
                <el-option
                  v-for="item in wDsList"
                  :key="item.id"
                  :label="item.datasourceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标数据源模式：" prop="targetSchema">
              <el-select
                v-model="temp.targetSchema"
                placeholder="请选择目标数据源模式"
              >
                <el-option
                  v-for="item in wSchemaList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务模板：" prop="jobTemplateId">
              <el-select
                v-model="temp.jobTemplateId"
                placeholder="请选择任务模板"
              >
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.jobDesc"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属项目：" prop="projectId">
              <el-select
                v-model="temp.projectId"
                placeholder="所属项目"
                class="filter-item"
              >
                <el-option
                  v-for="item in jobProjectList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="空间字段名称：">
              <el-input
                v-model="temp.spatialColumnName"
                placeholder="空间字段名称"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否开启自动检测任务创建：">
              <el-switch
                v-model="temp.status"
                active-color="#00A854"
                active-text="启动"
                :active-value="1"
                inactive-color="#F04134"
                inactive-text="停止"
                :inactive-value="0"
                @change="changeAddSwitch(temp.status)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as job from "@/api/datax-job-info";
import waves from "@/directive/waves"; // waves directive
import Cron from "@/components/Cron";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import JsonEditor from "@/components/JsonEditor";
import ShellEditor from "@/components/ShellEditor";
import PythonEditor from "@/components/PythonEditor";
import PowershellEditor from "@/components/PowershellEditor";

import * as jobProjectApi from "@/api/datax-job-project";
import { isJSON } from "@/utils/validate";
import {
  addAutoJob,
  deleteAutoJob,
  getAutoJobList,
  updateAutoJob
} from "@/api/datax-autoJob";

import { list as jdbcDsList } from "@/api/datax-jdbcDatasource";

import * as dsQueryApi from "@/api/metadata-query";
import * as jobTemp from "@/api/datax-job-template";

export default {
  name: "AutoJob",
  components: {
    Pagination,
    JsonEditor,
    ShellEditor,
    PythonEditor,
    PowershellEditor,
    Cron
  },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      projectIds: "",
      list: null,
      listLoading: true,
      total: 0,
      rDsList: [],
      wDsList: [],
      jobProjectList: [],
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      jdbcDsQuery: {
        current: 1,
        size: 200,
        ascs: "datasource_name"
      },
      schemaList: [],
      wSchemaList: [],
      templateList: [],
      showCronBox: false,
      dialogPluginVisible: false,
      pluginData: [],
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增"
      },
      rules: {
        sourceSourceId: [
          { required: true, message: "源数据源不能为空", trigger: "change" }
        ],
        sourceSchema: [
          { required: true, message: "源数据模式不能为空 ", trigger: "change" }
        ],
        targetSourceId: [
          { required: true, message: "目标数据源不能为空 ", trigger: "change" }
        ],
        targetSchema: [
          { required: true, message: "目标数据模式不能为空", trigger: "change" }
        ],
        projectId: [
          { required: true, message: "所属项目不能为空", trigger: "change" }
        ],
        jobTemplateId: [
          { required: true, message: "任务模板不能为空", trigger: "change" }
        ]
      },
      temp: {
        id: undefined,
        sourceSourceId: "",
        sourceSchema: "",
        targetSourceId: "",
        targetSchema: "",
        projectId: "",
        jobTemplateId: "",
        spatialColumnName: "geom",
        status: 0,
        lastSyncTime: ""
      }
    };
  },
  async created() {
    await this.getJdbcDs();
    await this.getJobProject();
    await this.getTempleteList();
    this.fetchData();
  },

  methods: {
    handleClose(done) {
      this.resetTemp();
      this.dialogFormVisible = false;
    },

    getJobProject() {
      jobProjectApi.getJobProjectList().then(response => {
        this.jobProjectList = response;
      });
    },
    resetTemp() {
      this.temp = this.$options.data().temp;
      /*   this.id= undefined
      this.temp.sourceSourceId=''
      this.temp.sourceSchema=''
      this.temp.targetSourceId=''
      this.temp.targetSchema=''
      this.temp.projectId=''
      this.temp.jobTemplateId=''
      this.temp.spatialColumnName='geom'
      this.temp.status=0*/
    },
    fetchData() {
      this.listLoading = true;

      getAutoJobList(this.listQuery).then(response => {
        this.total = response.total;

        this.list = response.records;
        this.listLoading = false;
      });
    },

    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          await addAutoJob(this.temp);
          this.dialogFormVisible = false;
          this.resetTemp();
          this.fetchData();
        }
      });
    },
    handlerUpdate(row) {
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      row.jobTemplateId = Number(row.jobTemplateId);
      row.projectId = Number(row.projectId);

      Object.assign(this.temp, row);
    },
    updateData() {
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          await updateAutoJob(this.temp);
          this.$message({
            message: "更新成功",
            type: "success"
          });
          this.dialogFormVisible = false;

          this.resetTemp();
          this.fetchData();
        }
      });
    },
    handlerDelete(row) {
      this.$confirm("确定删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteAutoJob(row.id).then(response => {
          this.fetchData();
          this.$notify({
            title: "Success",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
        });
      });

      // const index = this.list.indexOf(row)
    },

    handlerStart(row) {
      job.startJob(row.id).then(response => {
        this.$notify({
          title: "Success",
          message: "Start Successfully",
          type: "success",
          duration: 2000
        });
      });
    },
    handlerStop(row) {
      job.stopJob(row.id).then(response => {
        this.$notify({
          title: "Success",
          message: "Start Successfully",
          type: "success",
          duration: 2000
        });
      });
    },
    changeSwitch(row) {
      row.triggerStatus === 1 ? this.handlerStart(row) : this.handlerStop(row);
    },
    changeAddSwitch(val) {},

    // 获取可用数据源
    getJdbcDs(type) {
      jdbcDsList(this.jdbcDsQuery).then(response => {
        const { records } = response;
        this.rDsList = records;
        this.wDsList = records;
      });
    },
    rDsChange(e) {
      this.temp.sourceSchema = "";
      this.schemaList = [];
      this.getSchema("source");
    },
    getSchema(type) {
      if (type === "source") {
        let obj = {
          datasourceId: this.temp.sourceSourceId
        };
        dsQueryApi.getTableSchema(obj).then(response => {
          this.schemaList = response;
        });
      } else {
        let obj = {
          datasourceId: this.temp.targetSourceId
        };
        dsQueryApi.getTableSchema(obj).then(response => {
          this.wSchemaList = response;
        });
      }
    },

    wDsChange() {
      this.temp.targetSchema = "";
      this.wSchemaList = [];
      this.getSchema("targetSource");
    },
    getTempleteList() {
      let param = {
        current: 1,
        size: 1000,
        jobGroup: 0,
        triggerStatus: -1,

        userId: 0
      };
      jobTemp.getList(param).then(response => {
        this.templateList = response.content.data;
      });
    },

    getDictJdbcDsValue(val) {
      let dictValue = "";
      this.rDsList.forEach(item => {
        if (val === item.id) {
          dictValue = item.datasourceName;
        }
      });

      return dictValue;
    },

    getDictJobProjectValue(val) {
      let dictValue = "";
      this.jobProjectList.forEach(item => {
        if (val === item.id.toString()) {
          dictValue = item.name;
        }
      });

      return dictValue;
    },
    getDictTemplateValue(val) {
      let dictValue = "";
      this.templateList.forEach(item => {
        if (val === item.id.toString()) {
          dictValue = item.jobDesc;
        }
      })

      return dictValue
    }
  }
}
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
</style>
